#include "app.h"

#include "memdb/impl/mock/MockDB.h"

namespace app {

Application::Application()
: dataDir("./data")
, db(new memdb::impl::mock::MockDB)
{
}
Application::~Application(){
	if( db != nullptr) {
		delete db; 
		db = nullptr;
	}
}
void Application::run(){
	start();
	//......
	stop();
}

void Application::start(){
	db->recovery();
}
void Application::stop(){
	db->close();
}

}//namespace app
 


namespace app {

DataGrid::DataGrid() 
: _table(nullptr)
, _current(0)
, _pageSize(5)
{
}
DataGrid::~DataGrid(){
	_table = nullptr;
}

void DataGrid::setDataSource(memdb::ITable & table) {
	_table = &table;
	//reset the current  && many checks
	_current = 0;
}



// 0 - 1 = -1  ===> 0
// 1 - 1 = +0  ===> 0
// 2 - 1 = +1  ===> 1
// 2 - 10 = -8 ====> 0
int DataGrid::calcUp(int current, size_t step){
	if(current - (int)step >= 0){
		return current - (int)step;
	}
	return 0;
}
//TODO: testcase
int DataGrid::calcDown(int current, size_t step, size_t max){
	if(current + step <= max){
		return current + step;
	}
	return max;
}


void DataGrid::up(size_t cntRecord){
	_current = calcUp(_current, cntRecord);
	_table->range(_current, _pageSize);
}
void DataGrid::down(size_t cntRecord){
	_current = calcDown(_current, cntRecord, _table->count());
	_table->range(_current, _pageSize);
}

void DataGrid::pagesUp(size_t cntPages){
	_current = calcUp(_current, cntPages * _pageSize);
	_table->range(_current, _pageSize);
}
void DataGrid::pagesDown(size_t cntPages){
	_current = calcDown(_current, cntPages * _pageSize, _table->count());
	_table->range(_current, _pageSize);
}

}//namspace app
